package edu.ynu.e_platform.entities;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import edu.ynu.e_platform.common.entity.LogicEntity;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author manwen Yang
 */
@Entity(name = "torders")
@Getter
@Setter
@JsonIgnoreProperties(value = {"handler","hibernateLazyInitializer","fieldHandler"})
@Where(clause = "isDeleted = 0")  //逻辑删除,过滤掉删除标记不为0的
public class Order extends LogicEntity {

    @Column
    private Double totalPrice;

    /**
     *  订单状态，0未支付，1已支付，2已确认，3已退款
     */
    @Column(nullable = false,
            columnDefinition = "INT default 0")
    private Integer status;

    @ManyToOne(fetch = FetchType.LAZY)
    @JsonIgnoreProperties(value = {"orders"})
    private Customer customer;

    @ManyToOne(fetch = FetchType.LAZY)
    @JsonIgnoreProperties(value = {"orders","business","shopItems"})
    private Shop shop;

    @OneToMany(mappedBy = "order",
            fetch = FetchType.LAZY,
            orphanRemoval = true,  //在shopItem中删除记录，而不是将外键置为空
            cascade = CascadeType.ALL)  //级联更新
    @JsonIgnoreProperties(value = {"order"})
    private Set<LineItem> lineItems;

    public Order(){
        lineItems = new HashSet<>();
    }

    /**
     *  根据商品查找lineItem
     * @param item
     * @return lineItem
     */
    @JsonIgnore
    private LineItem findLineItem(Item item){
        AtomicReference<LineItem> result = new AtomicReference<>(null);

        if(lineItems==null){
            return result.get();
        }

        lineItems.forEach(lineItem -> {
            if(lineItem.getItem().getId().equals(item.getId())){
                result.set(lineItem);
            }
        });

        return result.get();
    }

    /**
     *  添加商品
     * @param item
     * @return lineItem
     */
    @JsonIgnore
    public LineItem addItem(Item item,Double quantity){

        LineItem lineItem = findLineItem(item);
        if (lineItem ==null) {
            lineItem = new LineItem();
            lineItem.setOrder(this);
            lineItem.setItem(item);
            lineItem.setQuantity(quantity);
            lineItems.add(lineItem);

            return lineItem;
        }else {
            var oldQuantity = lineItem.getQuantity();
            lineItem.setQuantity(oldQuantity+quantity);

            return lineItem;
        }
    }
    @JsonIgnore
    public LineItem addItem(Item item){
        return addItem(item,1.0);
    }

    /**
     *  计算总价
     * @param
     * @return
     */
    public void setTotalPrice(){
        if(lineItems.size() == 0){
            totalPrice = 0.0;
        }else {
            totalPrice = 0.0;
            for(LineItem lineItem : lineItems){
                totalPrice = totalPrice + lineItem.getItemTotlePrice();
            }
        }
    }
}
